import { useEffect, useMemo, useState } from "react";
import {
  Card,
  Table,
  Typography,
  Tag,
  Input,
  Space,
  Button,
  Select,
  DatePicker,
  Row,
  Col,
  message,
  Modal,
  Form,
  Descriptions,
  Spin,
} from "antd";
import {
  SearchOutlined,
  AuditOutlined,
  DeleteOutlined,
  ReloadOutlined,
} from "@ant-design/icons";
import dayjs from "dayjs";
import { isAdmin } from "../utils/auth";
import { useTheme } from "../contexts/ThemeContext";

import { fetchLogs, deleteLog, batchDeleteLogs } from "../api/logs";

const { Title, Text } = Typography;
const { RangePicker } = DatePicker;

const actionConfig = {
  add: { label: "新增", color: "green" },
  search: { label: "查询", color: "cyan" },
  edit: { label: "编辑", color: "blue" },
  delete: { label: "删除", color: "red" },
  publish: { label: "发布", color: "orange" },
  view: { label: "查看", color: "magenta" },
};

export default function Logs() {
  const { isDarkMode } = useTheme();
  const [formInstance] = Form.useForm();

  // 权限检查
  if (!isAdmin()) {
    return (
      <div style={{ maxWidth: 1200, margin: "20px auto", padding: "0 16px" }}>
        <Card style={{ textAlign: "center", padding: "60px 20px" }}>
          <Title level={3} type="danger">
            权限不足
          </Title>
          <Text type="secondary" style={{ fontSize: 16 }}>
            抱歉，您没有权限访问日志管理功能。只有管理员用户才能访问此页面。
          </Text>
        </Card>
      </div>
    );
  }

  // 状态管理
  const [logs, setLogs] = useState([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedLog, setSelectedLog] = useState(null);
  const [modalVisible, setModalVisible] = useState(false);
  const [deleteLoading, setDeleteLoading] = useState(false);

  // 过滤参数
  const [filters, setFilters] = useState({
    username: "",
    articleTitle: "",
    action: "",
    dateRange: [],
  });

  // 列定义（使用useMemo优化）
  const columns = useMemo(
    () => [
      {
        title: "用户",
        dataIndex: "username",
        key: "username",
        width: 100,
        render: (text) => <Tag color="geekblue">{text || "未知"}</Tag>,
      },
      {
        title: "文章",
        dataIndex: "article",
        key: "article",
        width: 150,
        ellipsis: true,
        render: (text) => <Tag color="green">{text || "无"}</Tag>,
      },
      {
        title: "操作",
        dataIndex: "action",
        key: "action",
        width: 80,
        render: (text) => {
          const config = actionConfig[text] || { label: text, color: "blue" };
          return <Tag color={config.color}>{config.label}</Tag>;
        },
      },
      {
        title: "内容",
        dataIndex: "content",
        key: "content",
        width: 200,
        ellipsis: true,
        render: (text) => (
          <Text ellipsis type="secondary">
            {typeof text === "string"
              ? text
              : JSON.stringify(text).slice(0, 100)}
          </Text>
        ),
      },
      {
        title: "消息",
        dataIndex: "msg",
        key: "msg",
        width: 150,
        ellipsis: true,
        render: (text) => <Text ellipsis>{text || "-"}</Text>,
      },
      {
        title: "时间",
        dataIndex: "createdAt",
        key: "createdAt",
        width: 170,
        sorter: (a, b) => new Date(a.createdAt) - new Date(b.createdAt),
        render: (text) => <Text type="secondary">{text}</Text>,
      },
      {
        title: "操作",
        key: "actions",
        width: 100,
        fixed: "right",
        render: (_, record) => (
          <Space size="small">
            <Button
              type="link"
              size="small"
              onClick={() => {
                setSelectedLog(record);
                setModalVisible(true);
              }}>
              详情
            </Button>
            <Button
              type="link"
              danger
              size="small"
              onClick={() => handleDeleteLog(record.id)}>
              删除
            </Button>
          </Space>
        ),
      },
    ],
    []
  );

  // 重新加载数据
  const reloadData = async () => {
    setLoading(true);
    try {
      const params = {
        page,
        size: pageSize,
      };

      if (filters.username) params.username = filters.username;
      if (filters.articleTitle) params.articleTitle = filters.articleTitle;
      if (filters.action) params.action = filters.action;
      if (filters.dateRange?.length === 2) {
        params.startTimes = filters.dateRange[0].format("YYYY-MM-DD HH:mm:ss");
        params.endTimes = filters.dateRange[1].format("YYYY-MM-DD HH:mm:ss");
      }

      const res = await fetchLogs(params);
      setTotal(res.total || 0);
      setLogs(
        (res.list || []).map((item) => ({
          id: item._id,
          username: item.username || item.userId,
          article:
            item.articleId === -1 ? "无" : item.articleTitle || item.articleId,
          action: item.action,
          content: item.content,
          msg: item.msg,
          createdAt:
            item.createdAt && item.createdAt.replace("T", " ").slice(0, 19),
          updatedAt:
            item.updatedAt && item.updatedAt.replace("T", " ").slice(0, 19),
        }))
      );
    } catch (error) {
      message.error("加载日志失败");
      setLogs([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载数据
  useEffect(() => {
    reloadData();
  }, [page, pageSize, filters]);

  // 删除单条日志
  const handleDeleteLog = async (id) => {
    Modal.confirm({
      title: "确认删除",
      content: "确定要删除这条日志吗？",
      okText: "确定",
      cancelText: "取消",
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          setDeleteLoading(true);
          await deleteLog(id);
          message.success("删除成功");
          reloadData();
        } catch (error) {
          message.error(error.message || "删除失败");
        } finally {
          setDeleteLoading(false);
        }
      },
    });
  };

  // 批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning("请选择要删除的项");
      return;
    }

    Modal.confirm({
      title: "确认批量删除",
      content: `确定要删除选中的 ${selectedRowKeys.length} 条日志吗？`,
      okText: "确定",
      cancelText: "取消",
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          setDeleteLoading(true);
          await batchDeleteLogs(selectedRowKeys.join(","));
          message.success("批量删除成功");
          setSelectedRowKeys([]);
          reloadData();
        } catch (error) {
          message.error(error.message || "批量删除失败");
        } finally {
          setDeleteLoading(false);
        }
      },
    });
  };

  // 应用过滤条件
  const handleFilter = () => {
    setPage(1);
  };

  // 重置过滤条件
  const handleReset = () => {
    formInstance.resetFields();
    setFilters({
      username: "",
      articleTitle: "",
      action: "",
      dateRange: [],
    });
    setPage(1);
  };

  return (
    <div style={{ maxWidth: 1400, margin: "0 auto", padding: "16px" }}>
      {/* 页面标题 */}
      <div style={{ textAlign: "center", marginBottom: 32 }}>
        <Title level={2} style={{ color: "#1890ff", marginBottom: 8 }}>
          <AuditOutlined /> 日志管理
        </Title>
        <Text type="secondary" style={{ fontSize: 16 }}>
          基于 NestJS 服务的操作日志记录与MongoDB存储
        </Text>
      </div>

      <Card
        style={{
          borderRadius: 12,
          boxShadow: isDarkMode
            ? "0 2px 12px rgba(0,0,0,0.3)"
            : "0 2px 12px #eee",
          backgroundColor: isDarkMode ? "#1f1f1f" : "#ffffff",
          borderColor: isDarkMode ? "#434343" : "#d9d9d9",
        }}>
        {/* 搜索过滤区域 */}
        <Card
          size="small"
          title={
            <Space>
              <SearchOutlined />
              <span>搜索条件</span>
            </Space>
          }
          style={{
            marginBottom: 24,
            backgroundColor: isDarkMode ? "#262626" : "#fafafa",
            borderColor: isDarkMode ? "#434343" : "#d9d9d9",
          }}>
          <Form form={formInstance} layout="inline">
            {/* 第一行：关键词搜索（占满一行） */}
            <Row gutter={[12, 12]} style={{ width: "100%" }}>
              <Col xs={24}>
                <Form.Item
                  name="keyword"
                  style={{ marginBottom: 0, width: "100%" }}>
                  <Input
                    placeholder="输入用户名或文章标题"
                    value={filters.username || filters.articleTitle}
                    onChange={(e) => {
                      const val = e.target.value;
                      setFilters({
                        ...filters,
                        username: val,
                        articleTitle: val,
                      });
                    }}
                    allowClear
                    prefix={<SearchOutlined />}
                  />
                </Form.Item>
              </Col>
            </Row>

            {/* 第二行:其他过滤条件 */}
            <Row gutter={[12, 12]} style={{ marginTop: 12, width: "100%" }}>
              <Col xs={24} sm={12} md={8}>
                <Form.Item
                  name="action"
                  style={{ marginBottom: 0, width: "100%" }}>
                  <Select
                    placeholder="选择操作类型"
                    value={filters.action || undefined}
                    onChange={(value) =>
                      setFilters({ ...filters, action: value || "" })
                    }
                    allowClear
                    style={{ width: "100%" }}>
                    {Object.entries(actionConfig).map(([key, value]) => (
                      <Select.Option key={key} value={key}>
                        {value.label}
                      </Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col xs={24} sm={12} md={8}>
                <Form.Item
                  name="dateRange"
                  style={{ marginBottom: 0, width: "100%" }}>
                  <RangePicker
                    showTime
                    style={{ width: "100%" }}
                    value={filters.dateRange}
                    onChange={(dates) =>
                      setFilters({ ...filters, dateRange: dates || [] })
                    }
                    placeholder={["开始时间", "结束时间"]}
                  />
                </Form.Item>
              </Col>
              <Col xs={24} sm={24} md={8}>
                <Form.Item style={{ marginBottom: 0, width: "100%" }}>
                  <Space style={{ width: "100%" }} wrap>
                    <Button
                      type="primary"
                      icon={<SearchOutlined />}
                      onClick={handleFilter}
                      loading={loading}>
                      搜索
                    </Button>
                    <Button
                      icon={<ReloadOutlined />}
                      onClick={reloadData}
                      loading={loading}
                      title="刷新日志列表">
                      刷新
                    </Button>
                    <Button onClick={handleReset}>重置</Button>
                  </Space>
                </Form.Item>
              </Col>
            </Row>

            {/* 第三行：批量操作 */}
            {selectedRowKeys.length > 0 && (
              <Row gutter={[12, 12]} style={{ marginTop: 12, width: "100%" }}>
                <Col xs={24}>
                  <Button
                    type="primary"
                    danger
                    loading={deleteLoading}
                    onClick={handleBatchDelete}>
                    删除选中的 {selectedRowKeys.length} 条日志
                  </Button>
                </Col>
              </Row>
            )}
          </Form>
        </Card>

        {/* 日志列表表格 */}
        <Spin spinning={loading}>
          <Table
            columns={columns}
            dataSource={logs}
            loading={loading}
            pagination={{
              current: page,
              pageSize: pageSize,
              total: total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条`,
              pageSizeOptions: ["10", "20", "50", "100"],
              onChange: (p, s) => {
                setPage(p);
                setPageSize(s);
              },
            }}
            rowSelection={{
              selectedRowKeys,
              onChange: setSelectedRowKeys,
            }}
            scroll={{ x: 1200 }}
            rowKey="id"
            style={{ marginTop: 16 }}
          />
        </Spin>
      </Card>

      {/* 详情模态框 */}
      <Modal
        title="日志详情"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setModalVisible(false)}>
            关闭
          </Button>,
        ]}
        width={800}
        styles={{
          content: {
            backgroundColor: isDarkMode ? "#141414" : "#ffffff",
          },
          header: {
            backgroundColor: isDarkMode ? "#1f1f1f" : "#ffffff",
            borderBottom: `1px solid ${isDarkMode ? "#434343" : "#f0f0f0"}`,
          },
        }}>
        {selectedLog && (
          <Descriptions
            column={1}
            bordered
            size="middle"
            style={{
              backgroundColor: isDarkMode ? "#262626" : "#fafafa",
            }}>
            <Descriptions.Item label="用户名">
              <Tag color="geekblue">{selectedLog.username}</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="文章">
              <Tag color="green">{selectedLog.article}</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="操作">
              {(() => {
                const config = actionConfig[selectedLog.action] || {
                  label: selectedLog.action,
                  color: "blue",
                };
                return <Tag color={config.color}>{config.label}</Tag>;
              })()}
            </Descriptions.Item>
            <Descriptions.Item label="消息">
              <Text>{selectedLog.msg || "-"}</Text>
            </Descriptions.Item>
            <Descriptions.Item label="内容">
              <pre
                style={{
                  background: isDarkMode ? "#1f1f1f" : "#f6f8fa",
                  padding: 12,
                  borderRadius: 4,
                  fontSize: "12px",
                  lineHeight: "1.4",
                  maxHeight: "300px",
                  overflow: "auto",
                  margin: 0,
                }}>
                {JSON.stringify(selectedLog.content, null, 2)}
              </pre>
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">
              <Text type="secondary">{selectedLog.createdAt}</Text>
            </Descriptions.Item>
            <Descriptions.Item label="更新时间">
              <Text type="secondary">{selectedLog.updatedAt}</Text>
            </Descriptions.Item>
          </Descriptions>
        )}
      </Modal>
    </div>
  );
}
